<template>
  <div>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px" size="small">
      <el-form-item label="计划名称" prop="planName">
        <el-input v-model="dataForm.planName" placeholder="计划名称" :maxlength="50"></el-input>
      </el-form-item>
      <el-form-item label="计划内容" prop="planContent">
        <el-input v-model="dataForm.planContent" placeholder="计划内容" :maxlength="200"></el-input>
      </el-form-item>
      <el-form-item label="计量器" prop="meterCodeName">
        <el-input placeholder="请选择计量器"
                  class="filter-item"
                  ref="meterObj"
                  @click.native="handleClick"
                  v-model="dataForm.meterCodeName">
        </el-input>
      </el-form-item>
      <el-form-item label="巡检周期" prop="planCycle">
        <el-radio-group v-model="dataForm.planCycle" @change="changeCycle(true)">
          <el-radio label="1">日</el-radio>
          <el-radio label="2">周</el-radio>
          <el-radio label="3">月</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="巡检日期" prop="planDate" v-if="dataForm.planCycle != '1'">
        <el-select v-model="dataForm.planDate" placeholder="巡检日期">
          <el-option
            v-for="item in dateOptions"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="开始日期" prop="effectTime">
        <el-date-picker
          v-model="dataForm.effectTime"
          type="date"
          placeholder="开始日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束日期" prop="expireTime">
        <el-date-picker
          v-model="dataForm.expireTime"
          type="date"
          placeholder="结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="时间段" prop="dateDataList">
        <el-table style="width: 100%" :data="dataForm.dateDataList" border  height="200" size="mini">
          <el-table-column label="开始时间" align="left" prop="startVal">
            <template slot-scope="scope">
              <el-time-select v-model="scope.row.startVal" size="mini" :picker-options="dataTimeOption"  style="width: 100%;" placeholder="请选择开始时间" :clearable=false> </el-time-select>
            </template>
          </el-table-column>
          <el-table-column label="结束时间" align="left" prop="endVal">
            <template slot-scope="scope">
              <el-time-select v-model="scope.row.endVal" size="mini" :picker-options="Object.assign({minTime:scope.row.startVal},dataTimeOption)"  style="width: 100%;" :clearable=false placeholder="请选择结束时间"> </el-time-select>
            </template>
          </el-table-column>
          <el-table-column align="right" width="70">
            <template slot="header">
              <el-button size="mini" icon="el-icon-plus" type="primary" @click="addDataList()"></el-button>
            </template>
            <template slot-scope="scope">
              <el-button size="mini" type="danger" icon="el-icon-minus" @click="handleDelete(scope.$index, scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item label="巡检人" prop="patrolUserId">
        <el-select v-model="dataForm.patrolUserId" filterable  placeholder="巡检人">
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.username"
            :value="item.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="巡检内容" prop="patrolContent">
        <el-input v-model="dataForm.patrolContent" placeholder="巡检内容" type="textarea" :maxlength="200"
                  :rows="2"></el-input>
      </el-form-item>
      <el-form-item label="巡检组长" prop="patrolLeaderUserId">
        <el-select v-model="dataForm.patrolLeaderUserId" filterable  placeholder="巡检组长">
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.username"
            :value="item.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核人" prop="auditUserId">
        <el-select v-model="dataForm.auditUserId" filterable  placeholder="审核人">
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.username"
            :value="item.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="dataForm.remark" placeholder="备注" type="textarea" :maxlength="200"
                  :rows="2"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false" size="small">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" size="small">确定</el-button>
    </span>
  </el-dialog>
  <el-dialog title="选择计量器" :visible.sync="showTree">
    <el-tree
      :style="'height:'+(containerHeight-100)+'px'"
      ref="buildTree"
      highlight-current
      node-key="id"
      :data="treeDataList"
      :expand-on-click-node="false"
      :props="menuListTreeProps"
      @node-click="selectBuild"
      default-expand-all
    >
        <span class="custom-tree-node"  slot-scope="{ node, data }">
          <span :dataType="data.type">
              <!-- <i class="el-icon-setting"  v-if="data.type=='b'"></i> -->
              <i class="el-icon-star-off"  v-if="data.type=='d'"></i>
              {{ node.label }}
          </span>
        </span>
    </el-tree>
    <div slot="footer" class="dialog-footer">
      <el-button @click="showTree = false">取 消</el-button>
    </div>
  </el-dialog>
  </div>
</template>

<script>
  import * as Util from "@/utils";
  export default {
    computed:{
      containerHeight() {
        return Util.getClientHeight() - 243;
      }
    },
    data () {
      return {
        menuListTreeProps: {
          label: "name",
          children: "children"
        },
        treeDataList:[],
        meterTypeList:[],
        collectTypeList:[],
        visible: false,
        userList:[],
        dateOptions : [],
        weekOptions : ["周一","周二","周三","周四","周五","周六","周日"],
        dayOptions : ["1号","2号","3号","4号","5号","6号","7号","8号","9号","10号","11号","12号","13号","14号","15号","16号","17号","18号","19号","20号","21号","22号","23号","24号","25号","26号","27号","28号","29号","30号","31号"],
        dataForm: {
          dateDataList:[],
          meterCodeName:'',
          planId: 0,
          planName: '',
          planContent: '',
          meterCode: '',
          planCycle: '1',
          planDate: '',
          effectTime: '',
          expireTime: '',
          patrolUserId: '',
          patrolContent: '',
          patrolLeaderUserId: '',
          auditUserId: '',
          projectId: this.$util.cookies.get("cuuren_projectId"),
          remark: ''
        },
        showTree :false,
        dataRule: {
          planName: [
            { required: true, message: '计划名称不能为空', trigger: 'blur' }
          ],
          planContent: [
            { required: true, message: '计划内容不能为空', trigger: 'blur' }
          ],
          meterCodeName: [
            { required: true, message: '计量器不能为空', trigger: 'blur' }
          ],
          planCycle: [
            { required: true, message: '巡检周期', trigger: 'blur' }
          ],
          planDate: [
            { required: true, message: '巡检日期', trigger: 'blur' }
          ],
          effectTime: [
            { required: true, message: '开始日期', trigger: 'blur' }
          ],
          expireTime: [
            { required: true, message: '结束日期', trigger: 'blur' }
          ],
          patrolUserId: [
            { required: true, message: '巡检人不能为空', trigger: 'blur' }
          ],
          patrolContent: [
            { required: true, message: '巡检内容不能为空', trigger: 'blur' }
          ],
          patrolLeaderUserId: [
            { required: true, message: '巡检组长不能为空', trigger: 'blur' }
          ],
          auditUserId: [
            { required: true, message: '审核人不能为空', trigger: 'blur' }
          ],
          projectId: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ],
          remark: [
            { required: true, message: '备注不能为空', trigger: 'blur' }
          ],
          dateDataList: [
            { required: true, message: '时间段', trigger: 'blur' }
          ]

        },
        dataTimeOption:{
          start: '00:00',
          step: '01:00',
          end: '23:59'
        }
      }
    },
    methods: {
      selectBuild(data){
        if(data.type=='d'){
          this.dataForm.meterCodeName = data.name;
          this.dataForm.meterCode = data.id;
          this.showTree = false;
        }
      },
      handleClick(event) {
        // 检查事件target是否不是清除按钮
        if (event.target.tagName != "INPUT") return;
        this.showTree = true
      },
      changeCycle(flag){
        this.dateOptions = []
        if(this.dataForm.planCycle == '2'){
          this.dateOptions = this.weekOptions
        }
        if(this.dataForm.planCycle == '3'){
          this.dateOptions = this.dayOptions
        }
        if(flag) {
          this.dataForm.planDate = this.dateOptions[0]
        }
        if(this.dataForm.planCycle == '1'){
          this.dataForm.planDate = ''
        }

      },
      addDataList(){
        this.dataForm.dateDataList.push({
          startVal:'00:00',
          endVal:'00:00',
        });
      },
      handleDelete(index,row){
        this.dataForm.dateDataList.splice(index,1);
      },
      init (id,userList,treeDataList,meterList) {
        this.dataForm.dateDataList=[]
        this.userList = userList
        this.treeDataList = treeDataList
        this.meterList = meterList
        this.dataForm.planId = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.planId) {
            this.$api.okhttp({
              url: this.$http.adornUrl(`/ecs/ecspatrolplan/info/${this.dataForm.planId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then((data) => {
              if (data && data.code === 0) {
                this.dataForm.planName = data.ecspatrolplan.planName
                this.dataForm.planContent = data.ecspatrolplan.planContent
                this.dataForm.meterCode = data.ecspatrolplan.meterCode
                this.dataForm.meterCodeName =  this.meterList.filter(ele=>ele.id === data.ecspatrolplan.meterCode && ele.type==='d')[0].name
                this.dataForm.planCycle = data.ecspatrolplan.planCycle
                this.dataForm.planDate = data.ecspatrolplan.planDate
                this.dataForm.effectTime = data.ecspatrolplan.effectDate
                this.dataForm.expireTime = data.ecspatrolplan.expireDate
                this.dataForm.patrolUserId = data.ecspatrolplan.patrolUserId
                this.dataForm.patrolContent = data.ecspatrolplan.patrolContent
                this.dataForm.patrolLeaderUserId = data.ecspatrolplan.patrolLeaderUserId
                this.dataForm.auditUserId = data.ecspatrolplan.auditUserId
                this.dataForm.projectId = data.ecspatrolplan.projectId
                this.dataForm.remark = data.ecspatrolplan.remark
                this.dataForm.dateDataList = data.ecspatrolplan.timeRange
                this.changeCycle(false)
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if(this.dataForm.effectTime>this.dataForm.expireTime){
              this.$message.error("开始日期不能大于结束时间")
              return ;
            }
            if( this.dataForm.dateDataList.length ===0){
              this.$message.error("开始时间和结束时间不能为空")
              return ;
            }
            this.$api.okhttp({
              url: this.$http.adornUrl(`/ecs/ecspatrolplan/${!this.dataForm.planId ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'planId': this.dataForm.planId || undefined,
                'planName': this.dataForm.planName,
                'planContent': this.dataForm.planContent,
                'meterCode': this.dataForm.meterCode,
                'planCycle': this.dataForm.planCycle,
                'planDate': this.dataForm.planDate,
                'effectDate': Util.dateFormat('YYYY-mm-dd HH:MM:SS',this.dataForm.effectTime),
                'expireDate': Util.dateFormat('YYYY-mm-dd HH:MM:SS',this.dataForm.expireTime),
                'patrolUserId': this.dataForm.patrolUserId,
                'patrolContent': this.dataForm.patrolContent,
                'patrolLeaderUserId': this.dataForm.patrolLeaderUserId,
                'auditUserId': this.dataForm.auditUserId,
                'projectId': this.dataForm.projectId,
                'remark': this.dataForm.remark,
                "customerId":this.$util.cookies.get('customer_id'),
                'timeRange':this.dataForm.dateDataList,

                // 'priceId': this.dataForm.priceId || undefined,
                // 'priceName': this.dataForm.priceName,
                // 'energyType': this.dataForm.energyType,
                // 'collectType': this.dataForm.collectType,
                // 'price': this.dataForm.price,
                // // 'startVal': this.dataForm.startVal.format('hh:mm:ss'),
                // // 'endVal': this.dataForm.endVal.format('hh:mm:ss'),
                // 'effectTime': Util.dateFormat('YYYY-mm-dd HH:MM:SS',this.dataForm.effectTime),
                // 'expireTime': Util.dateFormat('YYYY-mm-dd HH:MM:SS',this.dataForm.expireTime),
                // 'timeRange':this.dateDataList,
                // "customerId":this.$util.cookies.get('customer_id')
              })
            }).then((data) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      /**
       * 获取参数枚举
       */
      queryStatic(type,paramValue,callback) {
        let params = {
          'code': type ,
          "customerId":this.$util.cookies.get('customer_id')
        }
        if(paramValue){
          Object.assign(params,{...paramValue});
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then((data) => {
          if(callback){
            callback(data);
          }
        });
      }


    }
  }
</script>
